import type { FormInstance, UploadUserFile, UploadProps } from 'element-plus'
import type { ValuesType } from './typings'
import type { shareEnum } from '~/store/base/typings'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElForm,
  ElRow,
  ElCol,
  ElFormItem,
  ElInput,
  ElRadioGroup,
  ElRadioButton,
  ElIcon,
  ElUpload,
  ElImageViewer
} from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { GUTTER, SPAN_STYLE_LG_ONE_SM_DOUBLE } from '~/utils/const'
import { getToken } from '~/utils/auth'
import styles from '../index.module.scss'
import useVuexGetters from '~/hooks/useVuexGetters'

export default defineComponent({
  name: 'AssetLampBaseBasicInformation',
  props: ['detail', 'type'],
  setup: (props: { detail: ValuesType; type: string }, { expose }) => {
    const ruleFormRef = ref<FormInstance>()
    const baseState = useVuexGetters('base', ['usageStatusOpt'])
    const store = useStore()
    const fileList = ref<UploadUserFile[] | undefined>([])
    const optionsValidateForm = reactive<ValuesType>(
      Object.assign(
        {},
        props?.detail?.id // 初始化数据
          ? {
              id: props.detail.id,
              name: props.detail.name,
              useStatus: props.detail.useStatus,
              spec: props.detail.spec,
              constrUnit: props.detail.constrUnit,
              constrPerson: props.detail.constrPerson,
              stationName: props.detail.stationName,
              overallView: props.detail.overallView,
              memo: props.detail.memo
            }
          : {}
      )
    )

    onMounted(() => {
      //  使用状态
      store.dispatch('base/CabinetUseStatus', { code: 'asset_cabinet_use_status' })
      if (props?.detail?.id) {
        const images = (props.detail?.images && props.detail?.images?.split?.(',')) || []

        fileList.value = images.map((item) => ({
          name: '图片',
          url: item,
          response: {
            data: {
              link: item
            }
          }
        }))
      }
    })

    // 上传成功回调
    const handleUploadSuccess = (result: Record<string, any>) => {
      const link = result?.data?.link
      if (link) {
        fileList.value!.push({
          name: '图片',
          url: link,
          response: {
            data: {
              link
            }
          }
        })
      }
    }

    // 移除对应的文件
    const handleRemoveUploadFile = (file: Record<string, any>) => {
      fileList.value = fileList.value!.filter((item) => item.url !== file.response!.data!.link)
    }

    //  查看图片
    const imageUrl = ref<string[]>([])
    const initialIndex = ref(0)
    const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile: any) => {
      imageUrl.value = fileList.value!.map((item) => item.url || '')
      initialIndex.value = imageUrl.value.indexOf(uploadFile.response!.data!.link || '')
    }

    expose({ ruleFormRef, formValues: optionsValidateForm, fileList })

    return () => {
      return (
        <>
          <ElForm
            ref={ruleFormRef}
            model={optionsValidateForm}
            labelWidth="116px"
            labelPosition="right"
            class={styles['basicInformation-form']}
          >
            <ElRow gutter={GUTTER}>
              <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
                <ElFormItem
                  prop="name"
                  label="机柜名称"
                  rules={[
                    { required: true, whitespace: true, message: '请输入机柜名称', trigger: 'blur' }
                  ]}
                >
                  <ElInput
                    v-model={optionsValidateForm.name}
                    {...{ minlength: 2, maxlength: 50 }}
                    clearable
                    placeholder="请输入"
                  />
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
                <ElFormItem
                  prop="useStatus"
                  label="使用状态"
                  rules={[{ required: false, message: '请选择使用状态', trigger: 'change' }]}
                >
                  <ElRadioGroup
                    class={styles['info-form-item-full-width']}
                    v-model={optionsValidateForm.useStatus}
                  >
                    {baseState.usageStatusOpt.value?.map((item: shareEnum) => (
                      <ElRadioButton label={item.dictKey}>{item.dictValue}</ElRadioButton>
                    ))}
                  </ElRadioGroup>
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
                <ElFormItem
                  prop="spec"
                  label="规格型号"
                  rules={[
                    {
                      required: false,
                      whitespace: true,
                      message: '请输入规格型号',
                      trigger: 'blur'
                    }
                  ]}
                >
                  <ElInput
                    v-model={optionsValidateForm.spec}
                    {...{ maxlength: 50 }}
                    clearable
                    placeholder="请输入"
                  />
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
                <ElFormItem
                  prop="constrUnit"
                  label="施工单位"
                  rules={[
                    {
                      required: false,
                      whitespace: true,
                      message: '请输入施工单位',
                      trigger: 'blur'
                    }
                  ]}
                >
                  <ElInput
                    v-model={optionsValidateForm.constrUnit}
                    {...{ maxlength: 50 }}
                    clearable
                    placeholder="请输入"
                  />
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
                <ElFormItem
                  prop="constrPerson"
                  label="施工联系人"
                  rules={[
                    {
                      required: false,
                      whitespace: true,
                      message: '请输入施工联系人',
                      trigger: 'blur'
                    }
                  ]}
                >
                  <ElInput
                    v-model={optionsValidateForm.constrPerson}
                    {...{ maxlength: 50 }}
                    clearable
                    placeholder="请输入"
                  />
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
                <ElFormItem
                  prop="stationName"
                  label="关联基站"
                  rules={[
                    {
                      required: false,
                      whitespace: true,
                      message: '请输入关联基站',
                      trigger: 'blur'
                    }
                  ]}
                >
                  <ElInput
                    v-model={optionsValidateForm.stationName}
                    {...{ maxlength: 50 }}
                    clearable
                    placeholder="请输入"
                  />
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
                <ElFormItem
                  prop="overallView"
                  label="全景链接"
                  rules={[{ required: false, whitespace: true, message: '', trigger: 'blur' }]}
                >
                  <ElInput v-model={optionsValidateForm.overallView} clearable placeholder="" />
                </ElFormItem>
              </ElCol>

              <ElCol>
                <ElFormItem label="现场照片" prop="images">
                  <ElUpload
                    class={{ [styles['base-upload']]: true }}
                    action={'/api/gxsaas-system/oss/endpoint/put-file'}
                    headers={{ 'gxsaas-Auth': `bearer ${getToken()}` }}
                    {...{ drag: true, multiple: true }}
                    listType="picture-card"
                    fileList={fileList.value}
                    accept=".jpg,.png"
                    limit={50}
                    onSuccess={handleUploadSuccess}
                    onRemove={handleRemoveUploadFile}
                    onPreview={handlePictureCardPreview}
                  >
                    {/* 点击上传 */}
                    <ElIcon>
                      <UploadFilled />
                    </ElIcon>
                    <div class="el-upload__text">
                      拖拽照片到此区域可同时上传多张 <em>点击上传</em>
                    </div>
                  </ElUpload>
                </ElFormItem>
              </ElCol>

              <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
                <ElFormItem
                  prop="memo"
                  label="备注"
                  rules={[
                    {
                      required: false,
                      whitespace: true,
                      message: '请输入2~50字符',
                      trigger: 'blur'
                    }
                  ]}
                >
                  <ElInput
                    v-model={optionsValidateForm.memo}
                    {...{ maxlength: 200 }}
                    clearable
                    show-word-limit
                    type="textarea"
                    placeholder="请输入 最长200字符"
                  />
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElForm>
          {/* 图片显示 */}
          {!!imageUrl.value.length && (
            <ElImageViewer
              teleported
              initialIndex={initialIndex.value}
              urlList={imageUrl.value}
              onClose={() => {
                imageUrl.value = []
              }}
            />
          )}
        </>
      )
    }
  }
})
